import { isNumberical } from "./typeValidator";

// 接收enumlabel中的值生成ep-table中column的dicData值 isNumber判断是否需要把dict的key转成数字，用于回显
export function generateDicData(labelDict: Record<number | string, string>, isNumber = true) {
  const res: Record<string, string | number>[] = [];
  for (let [key, val] of Object.entries(labelDict)) {
    let value: string | number = key;
    if (isNumber && isNumberical(value)) value = +value;
    res.push({
      label: val,
      value,
    });
  }
  return res;
}

// 对象排序函数生成器，传入泛型和需要排序的字段名
export function createCompare<T>(
  key: keyof T,
  options: {
    defaultValue?: unknown;
    order?: "asc" | "desc";
    type?: "number" | "string";
  } = {}
) {
  const { defaultValue = 0, order = "asc", type = "number" } = options;

  return (a: T, b: T) => {
    let valueA = (a[key] as number) ?? defaultValue;
    let valueB = (b[key] as number) ?? defaultValue;
    let res = valueA - valueB;
    if ("string" === type) res = String(valueA).localeCompare(String(valueB));
    return "asc" === order ? res : -res;
  };
}
